package com.sunyzc.ebaotech.simulator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimulatorProperties {
	private static final Logger log = LoggerFactory.getLogger(SimulatorProperties.class);
	private static final String propertiesFile = "/simulator.properties";
	private static final Properties properties = loadProperties();

	private static Properties loadProperties() {
		Properties properties = new Properties();
		InputStream inputStream = null;
		try {
			inputStream = SimulatorProperties.class.getResourceAsStream(propertiesFile);
			properties.load(inputStream);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			IOUtil.closeQuietly(inputStream);
		}
		return properties;
	}

	public static synchronized String getTransCodePrefix() {
		return getProperty("transCodePrefix");
	}

	public static synchronized long getNextApplySerialNum() {
		long nextSerialNum = Long.parseLong(getProperty("currentApplySerialNum")) + 1;
		updateProperty("currentApplySerialNum", nextSerialNum + "");
		return nextSerialNum;
	}

	public static synchronized long getNextPolicySerialNum() {
		long nextSerialNum = Long.parseLong(getProperty("currentPolicySerialNum")) + 1;
		updateProperty("currentPolicySerialNum", nextSerialNum + "");
		return nextSerialNum;
	}

	public static synchronized String getNextPrintCode() {
		String nextPrintCode = String.format("%010d", Long.parseLong(getProperty("currentPrintCode")) + 1);
		updateProperty("currentPrintCode", nextPrintCode);
		return nextPrintCode;
	}

	public static String getProperty(String key) {
		return properties.getProperty(key);
	}

	private static void updateProperty(String key, String value) {
		OutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(new File(SimulatorProperties.class.getResource(propertiesFile).toURI().getPath()));
			// outputStream = new FileOutputStream(new File(URLDecoder.decode(SimulatorProperties.class.getResource(propertiesFile).getFile(),"UTF-8"))); // +号会有问题
			properties.setProperty(key, value);
			properties.store(outputStream, "");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			IOUtil.closeQuietly(outputStream);
		}
	}
}
